<template>
  <div class="page-container">
    <Position :menu-code="menuInfo.categoryId" :picture="rootMenuInfo.picture" :name="menuInfo.title" class="position"></Position>
    <div class="cus-container">
      <!-- A部分：产品主要信息区域 -->
      <div class="product-main-section">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 lg:gap-12">
          <!-- 左侧：轮播图区域 -->
          <div class="product-gallery">
            <div class="main-image-container relative bg-white rounded-lg border border-gray-200 p-4">
              <!-- UCarousel 主轮播图 -->
              <UCarousel
                ref="carousel"
                v-slot="{ item }"
                :items="thumbnailImages"
                :prev="{ onClick: onClickPrev }"
                :next="{ onClick: onClickNext }"
                class="w-full"
                @select="onSelect"
                autoplay
                :autoplay-delay="3000"
                :ui="{
                  container: 'relative w-full h-full',
                  item: 'w-full h-full flex-shrink-0'
                }"
              >
                <div class="main-image-wrapper relative overflow-hidden rounded-lg bg-gray-50 h-80 lg:h-96">
                  <NuxtImg :src="item.url || item" :alt="menuInfo.title" class="w-full h-full object-contain" />
                </div>
              </UCarousel>
            </div>

            <!-- 缩略图列表 -->
            <div v-if="thumbnailImages.length > 1" class="thumbnail-list mt-4">
              <div class="flex gap-2 justify-start overflow-x-auto px-4">
                <div
                  v-for="(image, index) in thumbnailImages"
                  :key="index"
                  class="thumbnail-item flex-shrink-0 cursor-pointer rounded-md overflow-hidden border-2 transition-all duration-200"
                  :class="{
                    'border-orange-500 ring-2 ring-orange-200': activeIndex === index,
                    'border-gray-200 hover:border-gray-300': activeIndex !== index
                  }"
                  @click="selectThumbnail(index)"
                >
                  <NuxtImg :src="image.url || image" :alt="`${menuInfo.title} 缩略图 ${index + 1}`" class="w-14 h-14 object-cover" />
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧：产品信息区域 -->
          <div class="product-info">
            <div class="space-y-6">
              <!-- 产品标题 -->
              <div class="product-header">
                <h1 class="text-2xl lg:text-3xl font-bold text-gray-900 mb-3 leading-tight">
                  {{ menuInfo.title }}
                </h1>
                <div class="text-sm text-gray-500 mb-4">产品简介：{{ menuInfo.subtitle || "柱型连续流动反应装置" }}</div>
              </div>

              <!-- 产品详细信息表格 -->
              <div class="product-details bg-gray-50 rounded-lg p-6">
                <div class="grid grid-cols-1 gap-4">
                  <!-- 产品编号 -->
                  <div class="detail-row flex items-center">
                    <div class="detail-label w-20 text-sm text-gray-600 flex items-center">
                      <Icon name="i-heroicons-hashtag" class="w-4 h-4 mr-1" />
                      产品型号：
                    </div>
                    <div class="detail-value text-sm font-medium text-gray-900">
                      {{ menuInfo.modelType || "MCR 1000型" }}
                    </div>
                  </div>

                  <!-- 更新时间 -->
                  <div class="detail-row flex items-center">
                    <div class="detail-label w-20 text-sm text-gray-600 flex items-center">
                      <Icon name="i-heroicons-calendar" class="w-4 h-4 mr-1" />
                      更新时间：
                    </div>
                    <div class="detail-value text-sm text-gray-900">
                      {{ formatDate(menuInfo.updatedAt) || "2023-08-16" }}
                    </div>
                  </div>

                  <!-- 访问量 -->
                  <div class="detail-row flex items-center">
                    <div class="detail-label w-20 text-sm text-gray-600 flex items-center">
                      <Icon name="i-heroicons-eye" class="w-4 h-4 mr-1" />
                      访问量：
                    </div>
                    <div class="detail-value text-sm text-gray-900">
                      {{ menuInfo.viewCount || 201 }}
                    </div>
                  </div>
                </div>
              </div>

              <!-- 联系方式区域 -->
              <div class="contact-section bg-orange-500 rounded-lg p-6 text-white">
                <div class="flex items-center justify-between">
                  <div class="contact-info">
                    <div class="flex items-center mb-2">
                      <Icon name="i-heroicons-phone" class="w-5 h-5 mr-2" />
                      <span class="text-sm">客服热线</span>
                    </div>
                    <div class="phone-number text-xl font-bold">
                      <NuxtLink :to="'tel:' + companyInfo.telephone">
                        {{ companyInfo.telephone }}
                      </NuxtLink>
                    </div>
                  </div>
                  <div class="contact-action">
                    <button class="text-orange-500 px-6 py-3 rounded-lg font-medium flex items-center">
                      立即咨询
                      <Icon name="i-heroicons-arrow-right" class="w-4 h-4 ml-2" />
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- B部分：详细内容区域 -->
      <div class="product-content-section mt-12 lg:mt-16">
        <div class="space-y-8">
          <!-- 产品描述 -->
          <div class="content-block">
            <h2 class="text-xl lg:text-2xl font-bold text-gray-900 mb-4">产品简介</h2>
            <div class="prose prose-lg max-w-none">
              <p class="text-gray-700 leading-relaxed">{{ menuInfo.description }}</p>
            </div>
          </div>

          <!-- 富文本内容 -->
          <div v-if="menuInfo.content" class="content-block">
            <h2 class="text-xl lg:text-2xl font-bold text-gray-900 mb-4">详细信息</h2>
            <div class="rich-content prose prose-lg max-w-none" v-html="menuInfo.content"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { NuxtLink } from "#components";
import { getDetailByLinkName } from "@/api/projects";
import Position from "~/components/Position.vue";
const route = useRoute();
const { id } = route.params;
const menuInfo = ref<any>({});
const rootMenuInfo = ref<any>({});
const appConfig = useAppConfig();
const { menus, companyInfo } = appConfig.systemConfig; // 菜单

// 轮播图相关状态
const carousel = useTemplateRef("carousel");
const activeIndex = ref(0);
const thumbnailImages = ref<any[]>([]);

/**
 * 初始化页面数据
 * 获取产品详情并查找对应的根节点菜单信息
 */
const initPage = async () => {
  try {
    const detail = await getDetailByLinkName(id as string);
    // 根据产品的categoryId查找对应的根节点菜单
    const rootMenu = useFindRootMenuByCode(menus, detail.categoryId);
    if (rootMenu) {
      rootMenuInfo.value = rootMenu;
    }
    if (detail) {
      menuInfo.value = detail;

      // 初始化图片数据
      initializeImages(detail);

      useHead({
        title: menuInfo.value.title,
        meta: [
          { name: "keywords", content: menuInfo.value.seoKey },
          { name: "description", content: menuInfo.value.description }
        ]
      });
    }
    console.log(detail, "产品详情");
  } catch (error) {
    console.error("初始化页面失败:", error);
  }
};

/**
 * 初始化图片数据
 * 合并mainImages和thumbnailImages
 */
const initializeImages = (detail: any) => {
  const images = [];

  // 添加主图
  if (detail.mainImages && detail.mainImages.length > 0) {
    images.push(...detail.mainImages);
  }

  // 添加缩略图（去重）
  if (detail.thumbnailImages && detail.thumbnailImages.length > 0) {
    detail.thumbnailImages.forEach((thumb: any) => {
      const imageUrl = thumb.url || thumb;
      if (!images.includes(imageUrl)) {
        images.push(thumb);
      }
    });
  }

  thumbnailImages.value = images;
};

/**
 * UCarousel 前一张图片
 */
const onClickPrev = () => {
  activeIndex.value--;
};

/**
 * UCarousel 下一张图片
 */
const onClickNext = () => {
  activeIndex.value++;
};

/**
 * UCarousel 选择回调
 * @param index - 选中的图片索引
 */
const onSelect = (index: number) => {
  activeIndex.value = index;
};

/**
 * 缩略图点击选择
 * @param index - 图片索引
 */
const selectThumbnail = (index: number) => {
  activeIndex.value = index;
  carousel.value?.emblaApi?.scrollTo(index);
};

/**
 * 格式化日期
 * @param dateString - 日期字符串
 */
const formatDate = (dateString: string) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit"
  });
};

initPage();
</script>

<style scoped lang="scss">
.page-container {
  min-height: 100vh;
  background: #f8fafc;
}

.product-main-section {
  padding: 2rem 0;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 2rem;
}

.product-gallery {
  .main-image-container {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  }

  .main-image-wrapper {
    background: #fafafa;

    img {
      transition: transform 0.3s ease;
    }

    &:hover img {
      transform: scale(1.02);
    }
  }
}

.thumbnail-list {
  max-width: 100%;
}

.thumbnail-item {
  transition: all 0.2s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.product-details {
  .detail-row {
    padding: 0.75rem 0;
    border-bottom: 1px solid #f1f5f9;

    &:last-child {
      border-bottom: none;
    }
  }

  .detail-label {
    min-width: 100px;
    font-weight: 500;
  }
}

.contact-section {
  background: linear-gradient(135deg, #f97316 0%, #ea580c 100%);
  box-shadow: 0 4px 16px rgba(249, 115, 22, 0.3);

  .phone-number {
    font-family: "Arial", sans-serif;
    letter-spacing: 1px;
  }

  button {
    transition: all 0.2s ease;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
  }
}

.product-description {
  p {
    text-align: justify;
    line-height: 1.7;
  }
}

.btn-primary {
  background: $custom-primary;
  color: white;
  border: none;
  display: inline-flex;
  align-items: center;
}

.btn-primary:hover {
  background: color-mix(in srgb, $custom-primary 90%, black);
}

.btn-secondary {
  background: transparent;
  color: $custom-primary;
  border: 2px solid $custom-primary;
  display: inline-flex;
  align-items: center;
}

.btn-secondary:hover {
  background: $custom-primary;
  color: white;
}

.content-block {
  background: white;
  padding: 2rem;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.rich-content {
  line-height: 1.8;
}

.rich-content table {
  width: 100%;
  border-collapse: collapse;
  margin: 1rem 0;
}

.rich-content table th,
.rich-content table td {
  border: 1px solid #e5e7eb;
  padding: 0.75rem;
  text-align: left;
}

.rich-content table th {
  background-color: #f9fafb;
  font-weight: 600;
}

.rich-content p {
  margin-bottom: 1rem;
}

.rich-content strong {
  font-weight: 600;
  color: #1f2937;
}

/* 响应式布局 */
@media (max-width: 1024px) {
  .product-main-section {
    padding: 1rem 0;
  }

  .content-block {
    padding: 1.5rem;
  }
}

@media (max-width: 768px) {
  .thumbnail-list .flex {
    justify-content: center;
  }

  .action-buttons .flex {
    flex-direction: column;
  }

  .action-buttons button {
    width: 100%;
    justify-content: center;
  }
}
</style>
